<template>
  <div class="site-reservation-detail">
    <div class="detail-header">
      <h3>{{ spot.name }} - 预约详情</h3>
      <p class="spot-description">{{ spot.description }}</p>
    </div>

    <div class="detail-content">
      <!-- 价格日历 -->
      <div class="price-calendar-section">
        <h4>价格日历</h4>
        <!-- 加载状态显示 -->
        <div v-if="loading" class="loading-indicator">
          <i class="fas fa-spinner fa-spin mr-2"></i> 加载价格信息中...
        </div>
        <!-- 日历显示 -->
        <div v-else class="calendar-container">
          <div class="calendar-header">
            <button @click="prevMonth" class="nav-btn">&lt;</button>
            <span class="month-year">{{ currentMonthYear }}</span>
            <button @click="nextMonth" class="nav-btn">&gt;</button>
          </div>
          <div class="calendar-grid">
            <div class="weekday" v-for="day in weekdays" :key="day">
              {{ day }}
            </div>
            <div
              v-for="date in calendarDates"
              :key="date.key"
              class="calendar-date"
              :class="{
                'other-month': !date.isCurrentMonth,
                selected: date.isSelected,
                available: date.isAvailable,
                unavailable: !date.isAvailable,
              }"
              @click="selectDate(date)"
            >
              <div class="date-number">{{ date.day }}</div>
              <div
                v-if="date.isCurrentMonth && date.isAvailable"
                class="date-info"
              >
                <div class="price">¥{{ date.price }}</div>
                <div class="stock">余{{ date.stock }}张</div>
              </div>
              <div
                v-else-if="
                  date.isCurrentMonth && !date.isAvailable && date.stock === 0
                "
                class="date-info"
              >
                <div class="unavailable-text">不可预约</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 左右分栏布局 -->
      <div class="two-column-layout">
        <!-- 左侧：景点信息 -->
        <div class="left-column">
          <div class="info-sections">
            <div class="info-section">
              <h4>预约须知</h4>
              <ul>
                <li v-for="notice in spot.notices" :key="notice">
                  {{ notice }}
                </li>
              </ul>
            </div>

            <div class="info-section">
              <h4>退款说明</h4>
              <p>{{ spot.refundPolicy }}</p>
            </div>

            <div class="info-section">
              <h4>使用说明</h4>
              <p>{{ spot.usageInstructions }}</p>
            </div>
          </div>
        </div>

        <!-- 右侧：预约功能 -->
        <div class="right-column">
          <!-- 门票数量选择 -->
          <div class="ticket-count-section">
            <div class="ticket-counter">
              <p style="font-weight: 600; font-size: 18px">门票数量</p>
              <button @click="decreaseCount" :disabled="ticketCount <= 1">
                -
              </button>
              <span class="count">{{ ticketCount }}</span>
              <button
                @click="increaseCount"
                :disabled="ticketCount >= maxTickets"
              >
                +
              </button>
            </div>
            <p class="ticket-limit">每次最多可预约{{ maxTickets }}张门票</p>
          </div>

          <!-- 游客信息填写 -->
          <TouristInfo
            :ticket-count="ticketCount"
            :selected-date="selectedDate"
            :spot="spot"
            :show-payment="!!selectedDate"
            @tourist-info-updated="onTouristInfoUpdated"
            @proceed-to-payment="proceedToPayment"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from "vue";
import TouristInfo from "./TouristInfo.vue";
import { getScenicDailyPrices } from "../../api/scenicSpots.js";

const props = defineProps({
  spot: {
    type: Object,
    required: true,
  },
  ticketCount: {
    type: Number,
    default: 1,
  },
});

const emit = defineEmits([
  "update-ticket-count",
  "date-selected",
  "tourist-info-updated",
  "proceed-to-payment",
]);

const currentDate = ref(new Date());
const selectedDate = ref(null);
const maxTickets = ref(10);
const scenicDailyPrices = ref([]); // 存储景点每日价格和库存信息
const loading = ref(false);

const weekdays = ["日", "一", "二", "三", "四", "五", "六"];

// 获取景点每日价格和库存信息
const fetchScenicDailyPrices = async () => {
  if (!props.spot.id) return;

  loading.value = true;
  try {
    // 调用API获取数据
    const prices = await getScenicDailyPrices(props.spot.id);
    scenicDailyPrices.value = prices;
  } catch (error) {
    console.error("获取景点每日价格失败:", error);
  } finally {
    loading.value = false;
  }
};

// 生成日历数据
const calendarDates = computed(() => {
  const year = currentDate.value.getFullYear();
  const month = currentDate.value.getMonth();

  const firstDay = new Date(year, month, 1);
  const lastDay = new Date(year, month + 1, 0);
  const startDate = new Date(firstDay);
  startDate.setDate(startDate.getDate() - firstDay.getDay());

  const dates = [];
  const today = new Date();

  for (let i = 0; i < 42; i++) {
    const date = new Date(startDate);
    date.setDate(startDate.getDate() + i);

    const isCurrentMonth = date.getMonth() === month;

    // 格式化日期为YYYY-MM-DD格式以匹配后端返回的ticketDate
    const dateString = date.toISOString().split("T")[0];

    // 查找是否有对应的每日价格和库存信息
    const dailyPrice = scenicDailyPrices.value.find(
      (item) => item.ticketDate === dateString
    );

    // 只有在后端返回数据中存在的日期才是可预约的
    const isAvailable =
      dailyPrice && date >= today && isCurrentMonth && dailyPrice.stock > 0;
    const price = dailyPrice ? dailyPrice.price : 0;
    const stock = dailyPrice ? dailyPrice.stock : 0;

    dates.push({
      key: date.toISOString(),
      day: date.getDate(),
      date: date,
      isCurrentMonth,
      isAvailable,
      isSelected:
        selectedDate.value &&
        date.toDateString() === selectedDate.value.toDateString(),
      price,
      stock,
    });
  }

  return dates;
});

const currentMonthYear = computed(() => {
  return currentDate.value.toLocaleDateString("zh-CN", {
    year: "numeric",
    month: "long",
  });
});

// 当景点ID变化时，重新获取每日价格信息
watch(
  () => props.spot.id,
  () => {
    fetchScenicDailyPrices();
  }
);

// 组件挂载时获取数据
onMounted(() => {
  fetchScenicDailyPrices();
});

const prevMonth = () => {
  currentDate.value = new Date(
    currentDate.value.getFullYear(),
    currentDate.value.getMonth() - 1,
    1
  );
};

const nextMonth = () => {
  currentDate.value = new Date(
    currentDate.value.getFullYear(),
    currentDate.value.getMonth() + 1,
    1
  );
};

const selectDate = (dateObj) => {
  if (!dateObj.isAvailable) return;

  selectedDate.value = dateObj.date;
  emit("date-selected", dateObj.date);
};

const decreaseCount = () => {
  if (props.ticketCount > 1) {
    emit("update-ticket-count", props.ticketCount - 1);
  }
};

const increaseCount = () => {
  if (props.ticketCount < maxTickets.value) {
    emit("update-ticket-count", props.ticketCount + 1);
  }
};

const onTouristInfoUpdated = (info) => {
  emit("tourist-info-updated", info);
};

const proceedToPayment = () => {
  emit("proceed-to-payment");
};

// 监听ticketCount变化
watch(
  () => props.ticketCount,
  (newCount) => {
    // 可以在这里添加额外的逻辑
  }
);
</script>

<style scoped>
.site-reservation-detail {
  background: white;
  border-radius: 12px;
  padding: 25px;
  margin-bottom: 30px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.detail-header h3 {
  font-size: 22px;
  color: #333;
  margin-bottom: 10px;
}

.spot-description {
  color: #666;
  font-size: 16px;
  margin-bottom: 25px;
}

.detail-content {
  display: grid;
  gap: 25px;
}

.two-column-layout {
  display: grid;
  grid-template-columns: 1fr 2fr;
  gap: 30px;
  margin-top: 25px;
}

.left-column {
  padding-right: 15px;
}

.right-column {
  padding-left: 15px;
  border-left: 1px solid #e0e0e0;
}

@media (max-width: 768px) {
  .two-column-layout {
    grid-template-columns: 1fr;
    gap: 20px;
  }

  .left-column,
  .right-column {
    padding: 0;
  }

  .right-column {
    border-left: none;
    border-top: 1px solid #e0e0e0;
    padding-top: 20px;
  }
}

.price-calendar-section {
  display: flex;
  align-items: center;
  flex-direction: column;
  /* justify-content: center; */
}

.price-calendar-section h4,
.ticket-count-section h4,
.info-section h4 {
  font-size: 18px;
  color: #333;
  margin-bottom: 15px;
}

.info-section h4 {
  text-align: center;
}

.ticket-count-section {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  margin-bottom: 10px;
  background: #fafafa;
  border-radius: 8px;
  padding: 20px;
}

/* 日历样式 */
.calendar-container {
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  width: 100%;
  text-align: center;
  overflow: hidden;
  margin-top: 15px;
}

.loading-indicator {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40px;
  color: #666;
}

.unavailable-text {
  color: #999;
  font-size: 12px;
  font-weight: bold;
}

.calendar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  background: #f5f5f5;
}

.nav-btn {
  background: var(--secondary-color);
  color: white;
  border: none;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  cursor: pointer;
  font-size: 16px;
}

.month-year {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.calendar-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
}

.weekday {
  padding: 10px;
  text-align: center;
  background: #f8f8f8;
  font-weight: bold;
  color: #666;
}

.calendar-date {
  min-height: 60px;
  padding: 8px;
  border: 1px solid #f0f0f0;
  cursor: pointer;
  transition: all 0.2s ease;
}

.calendar-date.available:hover {
  background: #f0f8f0;
}

.calendar-date.selected {
  background: var(--secondary-color);
  color: white;
}

.calendar-date.unavailable {
  background: #f5f5f5;
  color: #ccc;
  cursor: not-allowed;
}

/* 不可预约状态样式 */
.calendar-date.unavailable .unavailable-text {
  color: #999;
}

.calendar-date.other-month {
  color: #ccc;
}

.date-number {
  font-weight: bold;
  margin-bottom: 5px;
}

.date-info {
  font-size: 12px;
}

.price {
  color: var(--primary-color);
  font-weight: bold;
}

.stock {
  color: #666;
}

.calendar-date.selected .price,
.calendar-date.selected .stock {
  color: white;
}

/* 门票数量选择 */
.ticket-counter {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 10px;
}

.ticket-counter button {
  width: 40px;
  height: 40px;
  border: 1px solid #ddd;
  background: white;
  border-radius: 50%;
  cursor: pointer;
  font-size: 18px;
  font-weight: bold;
}

.ticket-counter button:hover:not(:disabled) {
  background: var(--secondary-color);
  color: white;
  border-color: var(--secondary-color);
}

.ticket-counter button:disabled {
  background: #f5f5f5;
  color: #ccc;
  cursor: not-allowed;
}

.count {
  font-size: 20px;
  font-weight: bold;
  min-width: 30px;
  text-align: center;
}

.ticket-limit {
  color: #666;
  font-size: 14px;
  margin: 0;
}

/* 信息区域 */
.info-sections {
  display: grid;
  gap: 20px;
}

.info-section {
  padding: 20px;
  background: #f9f9f9;
  border-radius: 8px;
}

.info-section ul {
  margin: 0;
  padding-left: 20px;
}

.info-section li {
  margin-bottom: 8px;
  color: #666;
}

.info-section p {
  margin: 0;
  color: #666;
  line-height: 1.6;
}
</style>
